//
//  ChatBubbleContentView.swift
//  Chatup
//
//  Created by iron man on 2024/2/19.
//

import Kingfisher
import SwiftUI

struct ChatBubbleContentView: View {
    @StateObject var viewModel: ChatBubbleContentViewModel
    var body: some View {
        if viewModel.needBubble {
            VStack(alignment: .leading) {
                if viewModel.model.messageType == .text {
                    ChatBubbleTextMessageView(viewModel: viewModel)
                } else if viewModel.model.messageType == .assetsImage {
                    
                    ChatBubbleAssetsImageMessageView(model: viewModel.model)
                } else {
                    ChatBubbleNetworkImageMessageView(viewModel: viewModel)
                }
            }
            .padding(viewModel.padding)
            .background(viewModel.model.isUser ? Color(red: 0.21, green: 0.84, blue: 0.54).opacity(0.7) : Color(red: 0.15, green: 0.15, blue: 0.2))
            .foregroundColor(.white)
            .cornerRadius(viewModel.model.isUser ? 8 : 0, corners: .topLeft)
            .cornerRadius(viewModel.model.isUser ? 0 : 8, corners: .topRight)
            .cornerRadius(8, corners: .bottomLeft)
            .cornerRadius(8, corners: .bottomRight)
        } else {
            // 文件类型消息体
            VStack {
                Text("📄")
                    .font(.system(size: 50).weight(.bold))
                    .foregroundColor(.black)
                Spacer().frame(height: 4)
                Text(viewModel.model.message)
                    .font(.system(size: 10))
                    .foregroundColor(.white)
            }
        }
    
    }
}

struct ChatBubbleTextMessageView: View {
    @StateObject var viewModel: ChatBubbleContentViewModel
    @State private var dots = "."
    @State private var timer: Timer?
    var body: some View {
        if viewModel.status == .loading {
            Text(viewModel.model.messageFeaturesType == .talk ? String.i18nText("chat_typing") + dots : String.i18nText("feature_draw_imagination_analyzing") + dots)
                .font(.system(size: 14))
                .onAppear {
                    self.timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { _ in
                        DispatchQueue.main.async {
                            self.dots += "."
                            if self.dots.count > 3 {
                                self.dots = "."
                            }
                        }
                    }
                }.onDisappear {
                    self.timer?.fire()
                    self.timer = nil
                }
        } else {
            VStack(alignment: viewModel.model.isUser ? .trailing : .leading) {
                if viewModel.status == .error {
                    Text("something wrong happens，please check your network and tetry")
                        .font(.system(size: 14))

                } else {
                    Text(viewModel.model.message)
                        .font(.system(size: 14))
                }

                if viewModel.needTool {
                    HStack {
                        Button(action: {
                            NotificationCenter.default.post(name: Notification.Name("kCopyMessage"), object: viewModel.model)
            
                        }, label: {
                            HStack {
                                Image("ic_copy")
                                Text(String.i18nText("chat_copy"))
                                    .font(Font.system(size: 12))
                                    .foregroundColor(.white.opacity(0.5))
                            }.padding(.horizontal, 10).padding(.vertical, 8).background(.white.opacity(0.05))
                                .cornerRadius(20)
                        })
                        if viewModel.model.isUser {
                            Button(action: {
                                NotificationCenter.default.post(name: Notification.Name("kReaskMessage"), object: viewModel.model)
                                //                        retryAction(model)
                            }, label: {
                                HStack {
                                    Image("ic_retry")
                                    Text(String.i18nText("reask"))
                                        .font(Font.system(size: 12))
                                        .foregroundColor(.white.opacity(0.5))
                                }.padding(.horizontal, 10).padding(.vertical, 8).background(.white.opacity(0.05))
                                    .cornerRadius(20)
                            })
                        } else {
                            Button(action: {
                                NotificationCenter.default.post(name: Notification.Name("kShareMessage"), object: viewModel.model)
                                //                        logAnswerShare()
                                //                        isShowingShareView.toggle()
                            }, label: {
                                HStack {
                                    Image("ic_share")
                                    Text(String.i18nText("chat_share"))
                                        .font(Font.system(size: 12))
                                        .foregroundColor(.white.opacity(0.5))
                                }.padding(.horizontal, 10).padding(.vertical, 8).background(.white.opacity(0.05))
                                    .cornerRadius(20)
                            })
                        }
                    }
                }
            }
        }
    }
}

struct ChatBubbleNetworkImageMessageView: View {
    @StateObject var viewModel: ChatBubbleContentViewModel
    @State private var dots = "."
    @State private var timer: Timer?
    var body: some View {
        if viewModel.status == .error {
            VStack(alignment: .leading) {
                Text("something wrong happens，please check your network and tetry")
                    .font(.system(size: 14))
                
                HStack {
                    Button(action: {
                        NotificationCenter.default.post(name: Notification.Name("kCopyMessage"), object: viewModel.model)
            
                    }, label: {
                        HStack {
                            Image("ic_copy")
                            Text(String.i18nText("chat_copy"))
                                .font(Font.system(size: 12))
                                .foregroundColor(.white.opacity(0.5))
                        }.padding(.horizontal, 10).padding(.vertical, 8).background(.white.opacity(0.05))
                            .cornerRadius(20)
                    })
                    if viewModel.model.isUser {
                        Button(action: {
                            NotificationCenter.default.post(name: Notification.Name("kReaskMessage"), object: viewModel.model)
                            //                        retryAction(model)
                        }, label: {
                            HStack {
                                Image("ic_retry")
                                Text(String.i18nText("reask"))
                                    .font(Font.system(size: 12))
                                    .foregroundColor(.white.opacity(0.5))
                            }.padding(.horizontal, 10).padding(.vertical, 8).background(.white.opacity(0.05))
                                .cornerRadius(20)
                        })
                    } else {
                        Button(action: {
                            NotificationCenter.default.post(name: Notification.Name("kShareMessage"), object: viewModel.model)
                            //                        logAnswerShare()
                            //                        isShowingShareView.toggle()
                        }, label: {
                            HStack {
                                Image("ic_share")
                                Text(String.i18nText("chat_share"))
                                    .font(Font.system(size: 12))
                                    .foregroundColor(.white.opacity(0.5))
                            }.padding(.horizontal, 10).padding(.vertical, 8).background(.white.opacity(0.05))
                                .cornerRadius(20)
                        })
                    }
                }
                
            }.padding(viewModel.padding)
                .background(viewModel.model.isUser ? Color(red: 0.21, green: 0.84, blue: 0.54).opacity(0.7) : Color(red: 0.15, green: 0.15, blue: 0.2))
                .foregroundColor(.white)
                .cornerRadius(viewModel.model.isUser ? 8 : 0, corners: .topLeft)
                .cornerRadius(viewModel.model.isUser ? 0 : 8, corners: .topRight)
                .cornerRadius(8, corners: .bottomLeft)
                .cornerRadius(8, corners: .bottomRight)
        } else {
            KFImage.url(URL(string: viewModel.model.message))
                .onSuccess { result in
                    viewModel.setStatus(s: .success)
                }
                .onFailure { error in
                    if viewModel.model.message.hasPrefix("http") {
                        viewModel.setStatus(s: .error)
                    }
                }
                .placeholder { _ in
                    if !viewModel.model.isUser {
                        LoadingTextView()
                    } else {
                        ProgressView()
                            .progressViewStyle(CircularProgressViewStyle(tint: .white))
                            .scaleEffect(2)
                    }
                }
                .cacheOriginalImage()
                .fade(duration: 1.0)
                .resizable()
                .scaledToFit()
                .frame(maxHeight: 180)
                .cornerRadius(viewModel.model.isUser ? 8 : 0, corners: .topLeft)
                .cornerRadius(viewModel.model.isUser ? 0 : 8, corners: .topRight)
                .cornerRadius(8, corners: .bottomLeft)
                .cornerRadius(8, corners: .bottomRight)
                .onTapGesture {
                    DispatchQueue.main.async {
                        NotificationCenter.default.post(name: Notification.Name("kOpenImageMessage"), object: viewModel.model)
                    }
                }
        }
    }
}

struct ChatBubbleAssetsImageMessageView: View {
    var model: MessageModel
    @State private var status: MessageStatus = .none
    @State private var isVip: Bool = UserDefaults.standard.bool(forKey: "kWhetherVip")
    @State private var dots = "."
    @State private var timer: Timer?
    var body: some View {
        if model.message.hasPrefix("http") {
            if status == .error {
                VStack(alignment: .leading) {
                    Text("something wrong happens，please check your network and tetry")
                        .font(.system(size: 14))
                    HStack {
                        Button(action: {
                            NotificationCenter.default.post(name: Notification.Name("kCopyMessage"), object: model)
                
                        }, label: {
                            HStack {
                                Image("ic_copy")
                                Text(String.i18nText("chat_copy"))
                                    .font(Font.system(size: 12))
                                    .foregroundColor(.white.opacity(0.5))
                            }.padding(.horizontal, 10).padding(.vertical, 8).background(.white.opacity(0.05))
                                .cornerRadius(20)
                        })
                        if model.isUser {
                            Button(action: {
                                NotificationCenter.default.post(name: Notification.Name("kReaskMessage"), object: model)
                                //                        retryAction(model)
                            }, label: {
                                HStack {
                                    Image("ic_retry")
                                    Text(String.i18nText("reask"))
                                        .font(Font.system(size: 12))
                                        .foregroundColor(.white.opacity(0.5))
                                }.padding(.horizontal, 10).padding(.vertical, 8).background(.white.opacity(0.05))
                                    .cornerRadius(20)
                            })
                        } else {
                            Button(action: {
                                NotificationCenter.default.post(name: Notification.Name("kShareMessage"), object: model)
                                //                        logAnswerShare()
                                //                        isShowingShareView.toggle()
                            }, label: {
                                HStack {
                                    Image("ic_share")
                                    Text(String.i18nText("chat_share"))
                                        .font(Font.system(size: 12))
                                        .foregroundColor(.white.opacity(0.5))
                                }.padding(.horizontal, 10).padding(.vertical, 8).background(.white.opacity(0.05))
                                    .cornerRadius(20)
                            })
                        }
                    }
                    
                }.padding(14)
                    .background(model.isUser ? Color(red: 0.21, green: 0.84, blue: 0.54).opacity(0.7) : Color(red: 0.15, green: 0.15, blue: 0.2))
                    .foregroundColor(.white)
                    .cornerRadius(model.isUser ? 8 : 0, corners: .topLeft)
                    .cornerRadius(model.isUser ? 0 : 8, corners: .topRight)
                    .cornerRadius(8, corners: .bottomLeft)
                    .cornerRadius(8, corners: .bottomRight)
            } else {
                KFImage.url(URL(string: model.message))
                    .onSuccess { result in
                        debugPrint("加载成功: \(result)")
                        self.status = .success
                    }
                    .onFailure { error in
                        if model.message.hasPrefix("http") {
                            self.status = .error
                        }
                    }
                    .placeholder { _ in
                        if !model.isUser {
                            LoadingTextView()
                        } else {
                            ProgressView()
                                .progressViewStyle(CircularProgressViewStyle(tint: .white))
                                .scaleEffect(2)
                        }
                    }
                    .cacheOriginalImage()
                    .fade(duration: 1.0)
                    .resizable()
                    .scaledToFit()
                    .frame(maxHeight: 180)
                    .cornerRadius(model.isUser ? 8 : 0, corners: .topLeft)
                    .cornerRadius(model.isUser ? 0 : 8, corners: .topRight)
                    .cornerRadius(8, corners: .bottomLeft)
                    .cornerRadius(8, corners: .bottomRight)
                    .onTapGesture {
                        NotificationCenter.default.post(name: Notification.Name("kOpenImageMessage"), object: model)
                    }
            }
                
        } else {
            ZStack(alignment: .bottom) {
                Rectangle()
                    .foregroundColor(.clear)
                    .frame(width: 179, height: 179)
                    .background(
                        Image(model.message)
                            .resizable()
                            .aspectRatio(contentMode: .fill)
                            .frame(width: 179, height: 179)
                            .clipped()
                    )
                    .cornerRadius(5)
                    .blur(radius: isVip ? 0 : 10)
                    .onTapGesture {
                        isVip = UserDefaults.standard.bool(forKey: "kWhetherVip")
                        if isVip {
                            NotificationCenter.default.post(name: Notification.Name("kOpenImageMessage"), object: model)
                        }
                    }

                if !isVip {
                    Button(action: {
                        NotificationCenter.default.post(name: Notification.Name("kOpenImageMessage"), object: model)
                    }) {
                        Text(String.i18nText("characters_pic_unlock"))
                            .font(.system(size: 12).bold())
                            .foregroundColor(.white)
                            .frame(width: 80, height: 30)
                            .background(Color(red: 0.15, green: 0.75, blue: 0.46))
                            .cornerRadius(15)
                            .shadow(color: .gray, radius: 5, x: 0, y: 0)
                    }
                }
            }.onAppear {
                isVip = UserDefaults.standard.bool(forKey: "kWhetherVip")
            }
        }
    }
}

struct LoadingTextView: View {
    let baseText: String = "正在加载"
    @State private var dots = ""
    @State private var timer: Timer?

    var body: some View {
        VStack {
            Image("ic_mofabang")
                .resizable()
                .frame(width: 50, height: 50)
            Spacer().frame(height: 8)
            Text("Drawing" + dots)
                .font(.system(size: 14).weight(.bold))
                .foregroundColor(.white)
                .frame(alignment: .leading)
                .onAppear {
                    self.timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { _ in
                        self.dots += "."
                        if self.dots.count > 3 {
                            self.dots = "."
                        }
                    }
                }.onDisappear {
                    self.timer?.fire()
                    self.timer = nil
                }
        }.frame(width: 180, height: 180)
            .background(
                Color(red: 20/255.0, green: 20/255.0, blue: 22/255.0))
    }
}
